"""通知服务模块"""
from typing import Dict, Any, List, Optional
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy import desc

from src.models.message import Notification
from src.models.user import User


class NotificationService:
    """通知服务类"""
    
    def create_notification(
        self,
        db: Session,
        user_id: int,
        title: str,
        content: str,
        type: str,
        related_id: Optional[int] = None
    ) -> Notification:
        """创建通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            title: 通知标题
            content: 通知内容
            type: 通知类型
            related_id: 相关ID（可选）
            
        Returns:
            创建的通知对象
        """
        notification = Notification(
            user_id=user_id,
            title=title,
            content=content,
            type=type,
            related_id=related_id,
            is_read=False
        )
        
        db.add(notification)
        db.commit()
        db.refresh(notification)
        
        return notification
    
    def get_user_notifications(
        self,
        db: Session,
        user_id: int,
        skip: int = 0,
        limit: int = 20,
        is_read: Optional[bool] = None,
        notification_type: Optional[str] = None
    ) -> List[Notification]:
        """获取用户通知列表
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            skip: 跳过的记录数
            limit: 返回的记录数
            is_read: 是否已读筛选（可选）
            notification_type: 通知类型筛选（可选）
            
        Returns:
            通知列表
        """
        query = db.query(Notification).filter(Notification.user_id == user_id)
        
        if is_read is not None:
            query = query.filter(Notification.is_read == is_read)
        
        if notification_type:
            query = query.filter(Notification.type == notification_type)
        
        return query.order_by(desc(Notification.created_at)).offset(skip).limit(limit).all()
    
    def get_notification_count(
        self,
        db: Session,
        user_id: int,
        is_read: Optional[bool] = None,
        notification_type: Optional[str] = None
    ) -> int:
        """获取用户通知数量
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            is_read: 是否已读筛选（可选）
            notification_type: 通知类型筛选（可选）
            
        Returns:
            通知数量
        """
        query = db.query(Notification).filter(Notification.user_id == user_id)
        
        if is_read is not None:
            query = query.filter(Notification.is_read == is_read)
        
        if notification_type:
            query = query.filter(Notification.type == notification_type)
        
        return query.count()
    
    def mark_as_read(
        self,
        db: Session,
        notification_id: int,
        user_id: int
    ) -> Optional[Notification]:
        """将通知标记为已读
        
        Args:
            db: 数据库会话
            notification_id: 通知ID
            user_id: 用户ID（用于权限验证）
            
        Returns:
            更新后的通知对象，如果不存在则返回None
        """
        notification = db.query(Notification).filter(
            Notification.id == notification_id,
            Notification.user_id == user_id
        ).first()
        
        if notification:
            notification.is_read = True
            db.commit()
            db.refresh(notification)
        
        return notification
    
    def mark_all_as_read(
        self,
        db: Session,
        user_id: int,
        notification_type: Optional[str] = None
    ) -> int:
        """将用户所有通知标记为已读
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            notification_type: 通知类型筛选（可选）
            
        Returns:
            更新的通知数量
        """
        query = db.query(Notification).filter(
            Notification.user_id == user_id,
            Notification.is_read == False
        )
        
        if notification_type:
            query = query.filter(Notification.type == notification_type)
        
        updated_count = query.update({"is_read": True}, synchronize_session=False)
        db.commit()
        
        return updated_count
    
    def delete_notification(
        self,
        db: Session,
        notification_id: int,
        user_id: int
    ) -> bool:
        """删除通知
        
        Args:
            db: 数据库会话
            notification_id: 通知ID
            user_id: 用户ID（用于权限验证）
            
        Returns:
            是否删除成功
        """
        notification = db.query(Notification).filter(
            Notification.id == notification_id,
            Notification.user_id == user_id
        ).first()
        
        if notification:
            db.delete(notification)
            db.commit()
            return True
        
        return False
    
    def create_system_notification(
        self,
        db: Session,
        user_id: int,
        content: str,
        related_id: Optional[int] = None
    ) -> Notification:
        """创建系统通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            content: 通知内容
            related_id: 相关ID（可选）
            
        Returns:
            创建的通知对象
        """
        return self.create_notification(
            db=db,
            user_id=user_id,
            title="系统通知",
            content=content,
            type="system",
            related_id=related_id
        )
    
    def create_trade_notification(
        self,
        db: Session,
        user_id: int,
        title: str,
        content: str,
        trade_id: int
    ) -> Notification:
        """创建交易相关通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            title: 通知标题
            content: 通知内容
            trade_id: 交易ID
            
        Returns:
            创建的通知对象
        """
        return self.create_notification(
            db=db,
            user_id=user_id,
            title=title,
            content=content,
            type="trade",
            related_id=trade_id
        )
    
    def create_message_notification(
        self,
        db: Session,
        user_id: int,
        sender_name: str,
        content: str,
        message_id: int
    ) -> Notification:
        """创建消息相关通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            sender_name: 发送者名称
            content: 通知内容
            message_id: 消息ID
            
        Returns:
            创建的通知对象
        """
        return self.create_notification(
            db=db,
            user_id=user_id,
            title=f"来自{sender_name}的消息",
            content=content,
            type="message",
            related_id=message_id
        )
    
    def create_product_notification(
        self,
        db: Session,
        user_id: int,
        title: str,
        content: str,
        product_id: int
    ) -> Notification:
        """创建商品相关通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            title: 通知标题
            content: 通知内容
            product_id: 商品ID
            
        Returns:
            创建的通知对象
        """
        return self.create_notification(
            db=db,
            user_id=user_id,
            title=title,
            content=content,
            type="product",
            related_id=product_id
        )
    
    def get_recent_notifications(
        self,
        db: Session,
        user_id: int,
        limit: int = 5
    ) -> List[Notification]:
        """获取用户最近的通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            limit: 返回的记录数
            
        Returns:
            最近的通知列表
        """
        return db.query(Notification).filter(
            Notification.user_id == user_id
        ).order_by(desc(Notification.created_at)).limit(limit).all()
    
    def delete_old_notifications(
        self,
        db: Session,
        user_id: int,
        days: int = 30
    ) -> int:
        """删除用户指定天数前的已读通知
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            days: 天数阈值
            
        Returns:
            删除的通知数量
        """
        cutoff_date = datetime.now() - timedelta(days=days)
        deleted_count = db.query(Notification).filter(
            Notification.user_id == user_id,
            Notification.is_read == True,
            Notification.created_at < cutoff_date
        ).delete(synchronize_session=False)
        
        db.commit()
        return deleted_count


# 导入timedelta
from datetime import timedelta

# 通知服务实例
notification_service = NotificationService()